package com.idc.resource.util;

import com.idc.resource.enums.ErrorCodeEnum;
import com.idc.resource.exception.IdcServiceException;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;


/**
 * 请求参数验证工具类
 * 验证失败，抛异常
 * Created by lijing on 16/9/6.
 */
@Slf4j
public class VerifyUtil {
    private final static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();


    /**
     * 请求参数非空、格式验证，请求对象
     * @param object 请求校验参数
     */
    public static void validateObject(Object object){
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Object>> violations = validator.validate(object);
        if (violations.size() == 0) return;
        for (ConstraintViolation<Object> violation : violations) {
            log.info("violation 信息:{}",violation.getPropertyPath().toString());
            throw new IdcServiceException(ErrorCodeEnum.PARAM_ERROR.getCode(), violation.getMessage());
        }
    }

    /**
     * 多个对象 请求参数非空、格式验证，请求对象
     * @param objects 请求校验参数
     */
    public static void validateObjects(Object... objects){
        for (Object obj:objects){
            validateObject(obj);
        }
    }

    /**
     * 请求参数校验 指定属性
     * @param object 请求校验参数
     */
    public static void validateProperty(Object object,String... properties){
        Validator validator = factory.getValidator();
        for (String property:properties){
            Set<ConstraintViolation<Object>> violations = validator.validateProperty(object,property);
            if (violations.size() == 0)  continue;
            for (ConstraintViolation<Object> violation : violations)
                throw new IdcServiceException(ErrorCodeEnum.PARAM_ERROR.getCode(), violation.getMessage());
        }
    }

    /**
     * 请求参数校验 不含指定属性
     * @param object 请求校验参数
     */
    public static void validateNoProperties(Object object,String... properties){
        Validator validator = factory.getValidator();
        Set<String> set = new HashSet<>(Arrays.asList(properties));
        Set<ConstraintViolation<Object>> violations = validator.validate(object);
        if (violations.size() == 0)  return;
        for (ConstraintViolation<Object> violation : violations) {
            if(!set.contains(violation.getPropertyPath().toString()))
                throw new IdcServiceException(ErrorCodeEnum.PARAM_ERROR.getCode(), violation.getMessage());
        }
    }
}


